<template>
	<view class="home">
		<custom-navbar title="信息提交" :show-back="true" @back="handleBack" />

		<view class="content pb150" :style="{ paddingTop: navBarHeight + 'px' }">
			<view class="w100 p2030">

				<view class="formdata">
					<up-form label-position="left" :model="formData" :rules="rules" ref="formRef">
						<view class="make p30 mb20">
							<up-form-item label="预约时段" :borderBottom="true" labelWidth="80" class="id-number-item"
								@click="showTimePicker = true">
								<up-input v-model="formData.reservation_time_display" class="id-number-input"
									placeholder="请选择预约时段" border="none" disabled disabledColor="#ffffff"
									inputAlign="right" style="width: 100%; padding-right: 20rpx;"></up-input>
								<template #right>
									<up-icon name="arrow-right"></up-icon>
								</template>
							</up-form-item>
							<up-form-item label="预约项目" :borderBottom="false" labelWidth="180">
								<up-input v-model="formData.project_name" placeholder="请选择预约项目" border="none" disabled
									disabledColor="#ffffff" inputAlign="right">
								</up-input>
							</up-form-item>
						</view>
						<view class="make p30">
							<up-form-item label="预约人" prop="reservation_person" :borderBottom="true" :required="true"
								labelWidth="180">
								<up-input v-model="formData.reservation_person" placeholder="请输入预约人" border="none"
									clearable inputAlign="right"></up-input>
							</up-form-item>

							<up-form-item label="身份证号" prop="id_number" :borderBottom="true" :required="true"
								labelWidth="180" class="id-number-item">
								<up-input v-model="formData.id_number" placeholder="请输入身份证号" border="none" clearable
									inputAlign="right" class="id-number-input"></up-input>
							</up-form-item>

							<up-form-item label="手机号" prop="phone_number" :borderBottom="true" :required="true"
								labelWidth="80">
								<up-input v-model="formData.phone_number" placeholder="请输入手机号" border="none" clearable
									inputAlign="right" type="number" maxlength="11"></up-input>
							</up-form-item>

							<up-form-item label="预约人数" :borderBottom="false" labelWidth="180" class="custom-form-item">
								<view class="tip-text-below-label">个人预约无需填写此项</view>
								<view class="fce person">
									<view class="fc">
										<up-button
											style="width: 60rpx; height: 60rpx; background: #398DFB; border-radius: 10rpx; opacity: 0.1;"
											type="primary" text="-" @click="decreaseNumber">
										</up-button>
										<view style="margin: 0 20rpx; font-size: 26rpx; color: #333333;">
											{{ formData.reservation_number }}
										</view>
										<up-button
											style="width: 60rpx; height: 60rpx; background: #398DFB; border-radius: 10rpx;"
											type="primary" text="+" @click="increaseNumber">
										</up-button>
										<view style="margin-left: 10rpx; font-size: 26rpx; color: #333333;">人</view>
									</view>
								</view>

							</up-form-item>
						</view>
					</up-form>
				</view>

				<view class="submit-btn">
					<up-button type="primary" text="提交报名信息" color="linear-gradient(90deg, #398DFB 0%, #61DBFF 100%)"
						:loading="submitting" @click="handleSubmit">
					</up-button>
				</view>
			</view>
		</view>
		<!-- 时间选择器 -->
		<up-datetime-picker v-model="timePickerValue" :show="showTimePicker" mode="datetime" :minDate="minDate"
			:maxDate="maxDate" @confirm="handleTimeConfirm" @cancel="showTimePicker = false">
		</up-datetime-picker>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		getCurrentInstance
	} from 'vue'
	import {
		saveReservation
	} from '@/api/plant'
	import CustomNavbar from '@/components/custom-navbar.vue'

	const {
		proxy
	} = getCurrentInstance()


	// 获取系统信息
	const systemInfo = uni.getSystemInfoSync()
	const navBarHeight = computed(() => systemInfo.statusBarHeight + 44)
	const showTimePicker = ref(false);
	const timePickerValue = ref(new Date().getTime());
	const minDate = new Date().getTime();
	const maxDate = new Date(new Date().setFullYear(new Date().getFullYear() + 1)).getTime();

	// 处理时间选择确认
	const handleTimeConfirm = (e) => {
		const date = new Date(e.value);
		const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
		const weekday = weekdays[date.getDay()];
		const month = (date.getMonth() + 1).toString().padStart(2, '0');
		const day = date.getDate().toString().padStart(2, '0');
		const hour = date.getHours().toString().padStart(2, '0');
		const formattedDate = date.toISOString().split('T')[0]; // YYYY-MM-DD

		formData.value.reservation_time = formattedDate; // 提交给接口
		// 格式化为：04月04日（周四）14:00~15:00
		formData.value.reservation_time_display = `${month}月${day}日（${weekday}）${hour}:00~${parseInt(hour)+1}:00`;
		formData.value.reservation_time_slot = `${hour}:00-${parseInt(hour)+1}:00`;
		formData.value.reservation_time = date.toISOString().split('T')[0];

		showTimePicker.value = false;
	};
	// 表单数据
	const formRef = ref(null)
	const submitting = ref(false)
	const formData = ref({
		project_id: '',
		space_id: '',
		reservation_time_slot: '',
		reservation_time_display: '',
		project_name: '',
		id_number: '',
		phone_number: '',
		reservation_person: '',
		reservation_number: 1,
		reservation_time: ''
	})

	// 表单验证规则
	const rules = {
		reservation_person: [{
			required: true,
			message: '请输入预约人姓名',
			trigger: 'blur'
		}, {
			min: 2,
			max: 10,
			message: '姓名长度在2-10个字符之间',
			trigger: 'blur'
		}],
		id_number: [{
			required: true,
			message: '请输入身份证号',
			trigger: 'blur'
		}, {
			validator: (rule, value, callback) => {
				if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
					callback(new Error('请输入正确的身份证号'))
				} else {
					callback()
				}
			},
			trigger: 'blur'
		}],
		phone_number: [{
			required: true,
			message: '请输入手机号',
			trigger: 'blur'
		}, {
			validator: (rule, value, callback) => {
				if (!/^1[3-9]\d{9}$/.test(value)) {
					callback(new Error('请输入正确的手机号'))
				} else {
					callback()
				}
			},
			trigger: 'blur'
		}]
	}

	// 初始化
	onMounted(() => {
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const options = currentPage.options

		// 从路由参数获取数据
		if (options.project_id) {
			formData.value.project_id = options.project_id
		}
		if (options.space_id) {
			formData.value.space_id = options.space_id
		}
		if (options.reservation_time_slot) {
			formData.value.reservation_time_slot = options.reservation_time_slot
		}
		if (options.reservation_time_display) {
			formData.value.reservation_time_display = options.reservation_time_display
		}
		if (options.project_name) {
			formData.value.project_name = options.project_name
		}
		if (options.reservation_time) {
			formData.value.reservation_time = options.reservation_time
		}
	})

	// 增加人数
	const increaseNumber = () => {
		formData.value.reservation_number += 1
	}

	// 减少人数
	const decreaseNumber = () => {
		if (formData.value.reservation_number > 1) {
			formData.value.reservation_number -= 1
		}
	}

	// 提交表单
	const handleSubmit = async () => {
		try {
			submitting.value = true

			// 验证表单
			await formRef.value.validate()

			// 调用API提交数据
			const res = await saveReservation({
				project_id: formData.value.project_id,
				space_id: formData.value.space_id,
				reservation_time_slot: formData.value.reservation_time_slot,
				id_number: formData.value.id_number,
				phone_number: formData.value.phone_number,
				reservation_person: formData.value.reservation_person,
				reservation_number: formData.value.reservation_number,
				reservation_time: formData.value.reservation_time
			})

			if (res.code === 200) {
				uni.showToast({
					title: '预约成功',
					icon: 'success'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} else {
				throw new Error(res.message || '预约失败')
			}
		} catch (error) {
			uni.showToast({
				title: error.message,
				icon: 'none'
			})
		} finally {
			submitting.value = false
		}
	}

	// 返回上一页
	const handleBack = () => {
		uni.navigateBack()
	}
</script>

<style lang="scss" scoped>
	.home {
		width: 100%;
		min-height: 100vh;
		position: relative;
		background-color: #f5f5f5;

		.content {
			padding-top: var(--status-bar-height);
			padding-top: calc(var(--status-bar-height) + 44px);
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: space-between;

			.formdata {
				width: 100%;
				margin-bottom: 40rpx;

				.id-number-item {

					// 穿透 uView 内部样式
					:deep(.u-form-item__body) {
						display: flex;
						align-items: center;
					}

					// 右侧内容区域占满剩余空间
					:deep(.u-form-item__body__right__content) {
						flex: 1;
						min-width: 0; // 关键：防止内容挤压
						margin-left: 20rpx; // 和左侧标签保持间距
					}
				}

				.full-width-input {
					// 输入框占满父容器
					width: 100%;

					// 输入框内部字段允许溢出
					:deep(.u-input__content__field-wrapper__field) {
						width: 100% !important;
						padding-right: 0;
						overflow: visible; // 允许内容溢出
						text-overflow: clip; // 不裁剪文本
					}

					// 调整清除按钮位置（避免遮挡）
					:deep(.u-input__content__clear) {
						right: 0;
					}
				}

				.make {
					background: #FFFFFF;
					border-radius: 20rpx;
				}

				.custom-form-item {
					position: relative;

					padding-bottom: 40rpx;
					padding-top: 20rpx;
					/* 为提示文字留出空间 */
					border-bottom: none !important;
				}

				.tip-text-below-label {
					position: absolute;
					left: 0rpx;
					/* 与label宽度一致 */
					bottom: 10rpx;
					font-size: 22rpx;
					color: #999999;
				}

				.person {
					position: absolute;
					right: 0;
					top: 40rpx;
				}
			}

			.submit-btn {
				position: fixed;
				bottom: 30rpx;
				left: 30rpx;
				right: 30rpx;

				.u-button {
					height: 90rpx;
					border-radius: 10rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: bold;
					font-size: 24rpx;
					color: #FFFFFF;
				}
			}
		}
	}
</style>